#include "ms575_algbackrightcircle.h"
using namespace MeasurE575;

AlgBackRightCircle::AlgBackRightCircle(int i):AlgBase(i)
{
}

void AlgBackRightCircle::operator()(cv::Mat &srcImg,
                                    int id,
                                    std::map<string, float> &measRes,
                                    int fixtureId)
{
    std::vector<cv::Point> resptVec;

    for(auto i=8;i<16;i++)
    {
        std::vector<int> tparas;
        for(auto j=0;j< m_dataAllVec[i].m_edgeParam.cols;j++)
        {
            tparas.push_back(m_dataAllVec[i].m_edgeParam.at<int>(i-8,j));
        }

        std::vector<cv::Rect> rangVec;
        TemplateMatch(srcImg,m_dataAllVec[i],rangVec);
        cv::Mat imgt=srcImg(rangVec[0]).clone();
        std::vector<cv::Point> contours;
        edgedetect obj;
        obj.NewCircleEdge(imgt,tparas,contours);
        ImageCoordinateTransformation(contours,rangVec);

        std::unique_lock<std::mutex> lock(*AlgBase::mtxptrVec[id]);
        while (!AlgBase::flagVec[id])
        {
            (*AlgBase::cvarptrVec[id]).wait(lock);
        }
        for(auto &elem:contours)
        {
            cv::Point2f ptsIn(static_cast<float>(elem.x),static_cast<float>(elem.y)),ptsOut;
            CoordinateTransformationRelateToDot(datumBackVec[id], ptsIn, ptsOut);
            resptVec.push_back(ptsOut);
        }
    }

    std::string prefix = m_xmlFileNamePre + to_string(fixtureId) + "_";
    edgedetect obj;
    vector<float> cirres=obj.FitCircle(resptVec);
    measRes.insert(std::make_pair(string("FAI39-R-X-distance_pixel"), -cirres[1]));
    float fai39rx = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI39-R-X-distance")], -cirres[1]);
    measRes.insert(std::make_pair(string("FAI39-R-X-distance_real"), fai39rx));

    measRes.insert(std::make_pair(string("FAI39-R-Y-distance_pixel"), -cirres[0]));
    float fai39ry = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI39-R-Y-distance")], -cirres[0]);
    measRes.insert(std::make_pair(string("FAI39-R-Y-distance_real"), fai39ry));

    CalcPosition("FAI39-R-X-distance", "FAI39-R-Y-distance", "FAI39-R-position", prefix,
                 obj, m_standardValMap["FAI39-R-X-distance"], m_standardValMap["FAI39-R-Y-distance"],
                 -cirres[1], -cirres[0], measRes);

    measRes.insert(std::make_pair(string("FAI38-R-diam_pixel"), cirres[2]*2));
    float fai38rd = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI38-R-diam")], cirres[2]*2);
    measRes.insert(std::make_pair(string("FAI38-R-diam_real"), fai38rd));

    float fai49=obj.GetRoundness(resptVec,cv::Point2f(cirres[0],cirres[1]));
    measRes.insert(std::make_pair(string("FAI49-R-roundness_pixel"), fai49));
    float fai49rr = CalcMeasureDistance(m_phypixpara[prefix + std::string("FAI49-R-roundness")], fai49);
    measRes.insert(std::make_pair(string("FAI49-R-roundness_real"), fai49rr));
}
